// https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
// 581. Shortest Unsorted Continuous Subarray
// Given an integer array nums, you need to find one continuous subarray that if
// you only sort this subarray in ascending order, then the whole array will be
// sorted in ascending order
// Return the shortest such subarray and output its length
export function findUnsortedSubarray(nums: number[]): number {
    let n = nums.length;
    let min = nums[n - 1];
    let max = nums[0];
    let begin = 0;
    let end = -1;
    for (let i = 0; i < n; i++) {
        if (nums[i] < max) {
            end = i;
        } else {
            max = nums[i];
        }

        if (nums[n - i - 1] > min) {
            begin = n - i - 1;
        } else {
            min = nums[n - i - 1];
        }
    }

    return end - begin + 1;
}
